package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.FreemarkerService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.ArticleVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author Du leilei
 * @version 1.0
 * @Description
 * @createTime 2023年09月04日 11:25:00
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private ApArticleContentMapper apArticleContentMapper;
    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    private FreemarkerService freemarkerService;
    @Autowired
    private CacheService cacheService;

    /**
     * app文章列表
     *
     * @param homeDto
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult load(ArticleHomeDto homeDto, int type) {
        //1.数据校验
        if (homeDto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.数据处理
        if (homeDto.getMaxBehotTime() == null) {
            homeDto.setMaxBehotTime(new Date(0L));
        }
        if (homeDto.getMinBehotTime() == null) {
            homeDto.setMinBehotTime(new Date());
        }
        if (homeDto.getSize() == 0 || homeDto.getSize() <= 0) {
            homeDto.setSize(10);
        } else {
            homeDto.setSize(Math.min(homeDto.getSize(), 30));
        }
        List<ApArticle> list = apArticleMapper.loadArticleList(homeDto, type);
        return ResponseResult.okResult(list);
    }

    /**
     * 同步自媒体文章到article数据库
     *
     * @param articleDto
     * @return
     */
    @Override
    public ResponseResult async(ArticleDto articleDto) {

        Long articleId = null;
        if (articleDto.getId() != null) {
            articleId = articleDto.getId();
            //修改
            ApArticle apArticle = new ApArticle();
            BeanUtils.copyProperties(articleDto, apArticle);
            apArticleMapper.updateById(apArticle);

            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(articleDto.getContent());
            apArticleContentMapper.update(apArticleContent, Wrappers.<ApArticleContent>lambdaUpdate()
                    .set(ApArticleContent::getContent, articleDto.getContent())
                    .eq(ApArticleContent::getArticleId, apArticleContent.getArticleId()));
        } else {
            //新增
            ApArticle apArticle = new ApArticle();
            BeanUtils.copyProperties(articleDto, apArticle);
            apArticleMapper.insert(apArticle);

            articleId = apArticle.getId();
            ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
            apArticleConfigMapper.insert(apArticleConfig);

            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(articleDto.getContent());
            apArticleContentMapper.insert(apArticleContent);
        }
        //生成文章详情

        freemarkerService.buildArticlePage(articleId, articleDto.getContent());

        return ResponseResult.okResult(articleId);
    }

    /**
     * 加载首页
     *
     * @param homeDto
     * @param type
     * @return
     */
    @Override
    public ResponseResult loadIndex(ArticleHomeDto homeDto, int type) {
        //查redis,拿热点文章返回
        String hotArticleListJSON = cacheService.get(ArticleConstants.HOT_ARTICLE + homeDto.getTag());
        if (StringUtils.isNotBlank(hotArticleListJSON)) {
            List<ArticleVO> articleVOList = JSON.parseObject(hotArticleListJSON, List.class);
            return ResponseResult.okResult(articleVOList);
        } else {
            return load(homeDto, type);
        }

    }

    @Override
    public ResponseResult saveArticle(ArticleDto dto) {
        //1.检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);

//2.判断是否存在id
        if (dto.getId() == null) {
            //2.1 不存在id  保存  文章  文章配置  文章内容

            //保存文章
            save(apArticle);

            //保存配置
            ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
            apArticleConfigMapper.insert(apArticleConfig);

            //保存 文章内容
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.insert(apArticleContent);

        } else {
            //2.2 存在id   修改  文章  文章内容

            //修改  文章
            updateById(apArticle);

            //修改文章内容
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, dto.getId()));
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.updateById(apArticleContent);
        }

        freemarkerService.buildArticlePage(apArticle.getId() , dto.getContent());


          //3.结果返回  文章的id
        return ResponseResult.okResult(apArticle.getId());
    }
}
